<?php

namespace VW\Common\LoginBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use VW\Common\LoginBundle\Entity\Users;

class DefaultController extends Controller {

    public function indexAction(Request $request) {
        if ($request->getMethod() == 'POST') {
            $username = $request->get('email');
            $password = $request->get('password');
            $em = $this->getDoctrine()->getManager();
            $repository = $em->getRepository('VWCommonLoginBundle:Users');
            $user = $repository->findOneBy(array('email' => $username, 'password' => $password));
            if ($user) {
                $name = strstr($user->getEmail(), '@', true);
                return $this->render('VWCommonLoginBundle:Default:login.html.twig', array('name' => $name));
            } else {
                return $this->render('VWCommonLoginBundle:Default:login.html.twig', array('error' => 'Email and password does not match.'));
            }
        }//end if

        return $this->render('VWCommonLoginBundle:Default:login.html.twig', array());
    }


    public function signupAction(Request $request) {
        if ($request->getMethod() == 'POST') {
            $username = $request->get('email');
            $password = $request->get('password');
            $full_name = $request->get('full_name');
            $gender = $request->get('gender');
            $dob = $request->get('dob');
            $em = $this->getDoctrine()->getManager();
            $repository = $em->getRepository('VWCommonLoginBundle:Users');
            $user = $repository->findOneBy(array('email' => $username));
            if (!$user) {
                $users = new Users();
                $users->setEmail($username);
                $users->setPassword($password);
                $users->setGender($gender);
                $users->setDob($dob);
                $users->setFullName($full_name);
                $users->setAccessLevel(1);
                $users->setCreated(date('Y-m-d H:i:s'));

                $em->persist($users);
                $em->flush();
                return $this->render('VWCommonLoginBundle:Default:signup.html.twig', array('name' => $full_name, 'msg' => 'You are successfully registerd on our site.'));
            } else {
                return $this->render('VWCommonLoginBundle:Default:signup.html.twig', array('error' => 'Email already exists in database, please choose another email.'));
            }
        }//end if

        return $this->render('VWCommonLoginBundle:Default:signup.html.twig', array());
    }
}
